﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Security.Cryptography;

using SBPweb.Forge.Contracts.Events;
using SBPweb.Forge.Contracts.Extensibility;

using SBPweb.Forge.Controls.Silverlight.Utilities;

using SBPweb.PROvibe.Business.Shared.Contracts.Content;
using SBPweb.PROvibe.Business.Shared.Contracts.Cryptography;

using SBPweb.PROvibe.Business.Client.Library.Content;
using SBPweb.PROvibe.Business.Client.Library.Modularity;
using SBPweb.PROvibe.Business.Client.Library.Services.LayoutConnector;

namespace SBPweb.PROvibe.Presentation.Client.Host
{

    public partial class App : Application, IContainer, IExtendable
    {

        #region Private fields

        private Dictionary<string, object> dictProperties = new Dictionary<string, object>();

        #endregion

        #region Constructor logic

        public App()
        {
            ContentManager.RegisterContainer(new ContainerDescriptor(ContainerIdConstants.RootVisual), this);

            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        #endregion

        #region Property accessors

        public ICollection<ContainerDescriptor> Containers
        {
            get
            {
                return new Collection<ContainerDescriptor>(new ContainerDescriptor[] { new ContainerDescriptor(ContainerIdConstants.RootVisual) });
            }
        }

        #endregion

        #region Methods

        #region Application life-cycle

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            InitializeParameters(e.InitParams);

            LayoutProviderClient lpc = new LayoutProviderClient();
            lpc.GetLayoutRootItemCompleted += new EventHandler<GetLayoutRootItemCompletedEventArgs>(OnGetLayoutRootItemCompleted);
#if CLIENTONLY
            lpc.GetLayoutRootItemSync(this.Host.Source.ToString());
#else
            lpc.GetLayoutRootItemAsync(this.Host.Source.ToString());
#endif
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void InitializeParameters(IDictionary<string, string> parameters)
        {
            if (parameters.ContainsKey("hash"))
            {
                foreach (KeyValuePair<string, string> kvp in InitialParametersHandler.DecryptParameters(parameters, SaltGenerator.CreateClientSalt()))
                {
                    Host.InitParams.Add(kvp);
                }
            }
        }

        private void OnGetLayoutRootItemCompleted(object sender, GetLayoutRootItemCompletedEventArgs e)
        {
            ModuleLoader.CreateInstance<Control>(e.Result.Descriptor, new EventHandler<ModuleLoaderObjectCreatedEventArgs<Control>>(OnRootItemCreated), e.Result);
        }

        private void OnRootItemCreated(object sender, ModuleLoaderObjectCreatedEventArgs<Control> e)
        {
            ContentItemDescriptor cId = e.UserState as ContentItemDescriptor;
            foreach (ContentItemDescriptor c in cId.Children)
            {
                ModuleLoader.CreateInstance<Control>(c.Descriptor, new EventHandler<ModuleLoaderObjectCreatedEventArgs<Control>>(OnRootItemCreated), c);
            }
        }

        #endregion

        #region Content management

        public void AssignContainerContent(ContainerDescriptor container, object content)
        {
            if (container.ContainerId == ContainerIdConstants.RootVisual)
            {
                this.RootVisual = content as UIElement;
            }
        }

        #endregion

        #region Extensibility

        public T Get<T>(string propertyName)
        {
            return (T)dictProperties[propertyName];
        }

        public void Put<T>(string propertyName, T value)
        {
            dictProperties[propertyName] = value;
        }

        #endregion

        #endregion

        #region Error handling

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }

        #endregion

    }

}